package com.tgl.vegetables.plug.meitu;

import android.accessibilityservice.AccessibilityService;
import android.graphics.Rect;
import android.os.Message;
import android.util.Log;
import android.view.accessibility.AccessibilityEvent;
import android.view.accessibility.AccessibilityNodeInfo;

import androidx.annotation.NonNull;

import com.tgl.vegetables.plug.service.BaseAccessibilityService;

import java.util.ArrayList;
import java.util.List;

public class MeituVegetablesAccessibilityService extends BaseAccessibilityService {
    private static final String TAG = "MeituAccessibilityService";

    private boolean mSelectedGoHomeTab = false;

    public MeituVegetablesAccessibilityService() {
        super();
        mHandler.removeMessages(MSG_CLICK_EVENT);
    }

    @Override
    public void onAccessibilityEvent(AccessibilityService context, AccessibilityEvent accessibilityEvent) {
        Log.e(TAG, "accessibilityEvent = " + accessibilityEvent.toString());
        super.onAccessibilityEvent(context, accessibilityEvent);
        int type = accessibilityEvent.getEventType();
        String className = accessibilityEvent.getClassName().toString();
        if (type == AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED) {
            switch (className) {
                case "com.meituan.retail.c.android.newhome.newmain.NewMainActivity":
                    mShopCarSelected = false;
                    mSelectedGoHomeTab = false;
                    processHomeActivity(accessibilityEvent);
                    break;
                case "com.meituan.retail.c.android.mrn.mrn.MallMrnActivity":
                    processOrderActivity(accessibilityEvent);
                    break;
                default:
                    break;
            }
        } else if(type == AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED){
            if (isCanNotOrderDialog(accessibilityEvent)) {
                //订单已约满
            }else if(isGoShopCarDialog(accessibilityEvent)){

            } else if (isSelectedTimePage(accessibilityEvent)) {
                processTimeSelectView(accessibilityEvent);
            }
        }
    }

    private boolean isSelectedTimePage(AccessibilityEvent accessibilityEvent){
        if (mCurrentWindow != WINDOW_ORDER) {
            return false;
        }
        AccessibilityNodeInfo root = accessibilityEvent.getSource();
        AccessibilityNodeInfo nodeInfo = findAccessibilityNodeInfo(root, "选择送达时间", 0);
        if(nodeInfo != null){
            mRootAccessibilityNodeInfo = root;
        }
        return nodeInfo != null;
    }

    private boolean isCanNotOrderDialog(AccessibilityEvent accessibilityEvent) {
        if (mCurrentWindow != WINDOW_ORDER) {
            return false;
        }
        AccessibilityNodeInfo root = accessibilityEvent.getSource();
        AccessibilityNodeInfo nodeInfo = findAccessibilityNodeInfo(root, "订单已约满", 0);
        if (nodeInfo == null) {
            return false;
        }
        nodeInfo = findAccessibilityNodeInfo(root, "我知道了", 0);
        if (nodeInfo != null) {
            mCurrentWindow = WINDOW_HOME;
            performClick(nodeInfo, 1);
            return true;
        }
        return false;
    }

    private boolean isGoShopCarDialog(AccessibilityEvent accessibilityEvent) {
        if (mCurrentWindow != WINDOW_ORDER) {
            return false;
        }
        AccessibilityNodeInfo root = accessibilityEvent.getSource();
        AccessibilityNodeInfo nodeInfo = findAccessibilityNodeInfo(root, "前方拥堵，请稍后再试", 0);
        if (nodeInfo == null) {
            return false;
        }
        nodeInfo = findAccessibilityNodeInfo(root, "返回购物车", 0);
        if (nodeInfo != null) {
            mCurrentWindow = WINDOW_HOME;
            performClick(nodeInfo, 1);
            return true;
        }
        return false;
    }

    private void processHomeActivity(AccessibilityEvent accessibilityEvent) {
        mRootAccessibilityNodeInfo = accessibilityEvent.getSource();
        if (!mShopCarSelected) {
            mShopCarSelected = doSelectShopCar(accessibilityEvent.getSource());
        }
        mCurrentWindow = WINDOW_HOME;
        mHandler.removeMessages(MSG_CLICK_EVENT);
        mHandler.sendEmptyMessageDelayed(MSG_CLICK_EVENT, getDuration());
    }

    private void processOrderActivity(AccessibilityEvent accessibilityEvent) {
        mRootAccessibilityNodeInfo = accessibilityEvent.getSource();
        mCurrentWindow = WINDOW_ORDER;
        mHandler.removeMessages(MSG_CLICK_EVENT);
        mHandler.sendEmptyMessageDelayed(MSG_CLICK_EVENT, getDuration());
    }

    private void processTimeSelectView(AccessibilityEvent accessibilityEvent) {
        mHandler.removeMessages(MSG_CLICK_EVENT);
        mCurrentWindow = WINDOW_SELECT_TIME;
        mRootAccessibilityNodeInfo = accessibilityEvent.getSource();
        mHandler.sendEmptyMessageDelayed(MSG_CLICK_EVENT, getDuration());
    }

    private boolean doSelectShopCar(AccessibilityNodeInfo nodeInfo) {
        nodeInfo = findAccessibilityNodeInfoViewId(nodeInfo, "com.sankuai.meituan:id/img_shopping_cart", 0);
        if (nodeInfo != null) {
            performClick(nodeInfo, 1);
            return nodeInfo.isSelected();
        }
        return false;
    }

    @Override
    protected long getDuration() {
        switch (mCurrentWindow){
            case WINDOW_HOME:
                return 1000;
            case WINDOW_SELECT_TIME:
                return 500;
            default:
                return 200;
        }
    }

    private void onClickCalc() {
        if (!mShopCarSelected) {
            mShopCarSelected = doSelectShopCar(mAccessibilityService.getRootInActiveWindow());
        }
        AccessibilityNodeInfo root = mRootAccessibilityNodeInfo;
        if (root == null) {
            root = mAccessibilityService.getRootInActiveWindow();
        }

        AccessibilityNodeInfo nodeInfo = findAccessibilityNodeInfo(root, "当前不在可下单时段", 0);
        AccessibilityNodeInfo nodeInfo1 = findAccessibilityNodeInfo(root, "我知道了", 0);
        if (nodeInfo != null && nodeInfo1 != null) {
            performClick(nodeInfo1, 1);
            return;
        }

        nodeInfo = findAccessibilityNodeInfo(mAccessibilityService.getRootInActiveWindow(), "结算", 0);
        if (nodeInfo != null) {
            performClick(nodeInfo, 1);
        }
    }

    private void onClickOrder() {
        AccessibilityNodeInfo root = mAccessibilityService.getRootInActiveWindow();
        if (root == null) {
            root = mRootAccessibilityNodeInfo;
        }

        AccessibilityNodeInfo nodeInfo = findAccessibilityNodeInfo(root, "送货上门", 0);
        if(nodeInfo != null && !mSelectedGoHomeTab){
            performClick(nodeInfo,1);
            mSelectedGoHomeTab = true;
        }

        nodeInfo = findAccessibilityNodeInfo(root, "立即支付", 0);
        if (nodeInfo == null) {
            nodeInfo = findAccessibilityNodeInfo(root, "极速支付", 0);
        }

        if(nodeInfo != null){
            performClick(nodeInfo, 1);
        }
    }

    private void onClickTimeSelect() {
        mCurrentWindow = WINDOW_ORDER;
        AccessibilityNodeInfo root = mRootAccessibilityNodeInfo;
        if (root == null) {
            root = mAccessibilityService.getRootInActiveWindow();
        }

        List<String> times = new ArrayList<>();
        times.add("09:00-09:30");
        times.add("09:30-10:00");
        times.add("10:00-10:30");
        times.add("10:30-11:00");
        times.add("11:00-11:30");
        times.add("15:00-15:30");
        times.add("15:30-16:00");
        times.add("16:00-16:30");
        times.add("16:30-17:00");
        times.add("17:00-17:30");
        times.add("18:30-18:00");
        times.add("18:00-18:30");
        boolean canNotOrder = false;
        boolean noFoundTime = true;
        for (String time : times) {
            AccessibilityNodeInfo nodeInfo = findAccessibilityNodeInfo(root, time, 0);
            if (nodeInfo != null) {
                noFoundTime = false;
                AccessibilityNodeInfo parent = nodeInfo.getParent();
                int childCount = parent.getChildCount();
                for (int i = 0; i < childCount; i++) {
                    AccessibilityNodeInfo child = parent.getChild(i);
                    if (child.getText() != null && child.getText().toString().contains("已约满")) {
                        canNotOrder = true;
                        break;
                    }
                    try {
                        Log.e(TAG, parent.getChild(i).getText().toString());
                    }catch (Exception e) {

                    }
                }
                if (!canNotOrder) {
                    Rect rect = new Rect();
                    parent.getBoundsInScreen(rect);
                    autoClickPoint(rect.left + 10,rect.top + 10);
                    return;
                }
            }
        }

        if(noFoundTime){
            AccessibilityNodeInfo nodeInfo = findAccessibilityNodeInfo(root, "选择送达时间", 0);
            if(nodeInfo != null){
                Rect rect = new Rect();
                nodeInfo.getBoundsInScreen(rect);
                autoClickPoint(rect.left + 10,rect.top + 200);
            }
        }

    }
    private void onClick() {
        switch (mCurrentWindow) {
            case WINDOW_HOME:
                onClickCalc();
                break;
            case WINDOW_ORDER:
                onClickOrder();
                break;
            case WINDOW_SELECT_TIME:
                onClickTimeSelect();
                break;
            default:
                break;
        }
    }

    @Override
    public boolean handleMessage(@NonNull Message message) {
        switch (message.what) {
            case MSG_CLICK_EVENT:
                onClick();
                mHandler.sendEmptyMessageDelayed(MSG_CLICK_EVENT, getDuration());
                break;
            default:
                break;
        }
        return false;
    }
}
